/*  header-comment
/*  file   : /Users/allan/Desktop/workSpace/react-hrm-h5/src/modules/preJobList/index
/*  author : Allan
/*  date   : 2017-09-09 23:17
/*  last   : 2017-10-2 11:44:13
*/
import React, { Component } from "react";
import PropTypes from "prop-types";
import { bindActionCreators } from "redux";
import { connect } from "react-redux";
import { List, ListView, Icon, WhiteSpace } from "@ali/ding-ui";

import { getLists } from "../../actions/preJobList/";
import "./index.less";

import { mid2Url } from "@ali/ding-mediaid";
import autobind from "autobind-decorator";
// componet
import DDAvatar from "../../components/Avatar/";
import { setTitle, setRight, openLink } from "../../utils/dingtalk.js";
import { replaceSearch } from "../../utils/urlParams";
import { set, get } from "../../utils/db";
import lwp from '../../utils/lwp.js'
import TitleBage from "../../components/TitleBage"
const Item = List.Item;
const Brief = Item.Brief;

const PAGE_SIZE = 15;

const mapStateToProps = () => ({});
const mapDispatchToProps = dispatch => ({
    actions: bindActionCreators(
        {
            dispatch,
            getLists
        },
        dispatch
    )
});
function getFromMessage(opUserName, opSourceType) {
    if (!opSourceType && !opUserName) return "未知的来源添加";
    if (!opSourceType) return `${opUserName}添加`;
    if (!opUserName) return `${opSourceType}添加`;
    if (opSourceType === '二维码') return `${opUserName}分享的${opSourceType}办理入职`;
    return `${opUserName}的${opSourceType}添加`;
}
@connect(mapStateToProps, mapDispatchToProps)
export default class PreJobList extends Component {
    static propTypes = {
        actions: PropTypes.shape({
            dispatch: PropTypes.func.isRequired,
            getLists: PropTypes.func.isRequired
        }).isRequired
    };
    constructor(props) {
        super(props);
        const dataSource = new ListView.DataSource({
            rowHasChanged: (row1, row2) => row1 !== row2
        });
        setRight({ show: false })
        setTitle({ title: "办理入职" });
        this.state = {
            needLoad: false,
            aflowLoad:false,
            dataSource,
            isLoading: true,
            refreshing: false,
            height: document.body.clientHeight,

            // 当前页码
            pageIndex: 1,
            hasMore: false,
            data: [],
            prePage: 1,
            total: "",
            showTip: false // tips 目前默认先不显示，需求有变更 -20171031-媛英
        };
    }

	/**
	 * 进入页面加载初始列表
	 * */
    componentWillMount() {
        this.getLists(1);
    }

    componentWillUnmount() {
        window.needReload = null;
    }

    //待刷新
    needReload() {
        const me = this;
        window.needReload = function () {
            if (window.location.href.indexOf("preJobList") !== -1 && me.state.needLoad) {
                me.setState({
                    dataSource: me.state.dataSource,
                    refreshing: false,
                    isLoading: true,
                    pageIndex: 1,
                    needLoad:false,
                    hasMore: false,
                    data: []
                }, () => {
                    me.getLists(1,false);
                });
            }
            if(window.location.href.indexOf("preJobList") !== -1 && me.state.aflowLoad){
                me.setState({
                    aflowLoad:false,
                    dataSource: me.state.dataSource,
                    refreshing: false,
                    isLoading: true,
                    pageIndex: 1,
                    needLoad:false,
                    hasMore: false,
                    data: []
                },()=>{
                    me.getHandleEntry();
                    me.getLists(1,false);
                })
            }
        };
    }

    getHandleEntry() {
        const data = [
            get('corpId')
        ]
        console.log("handleEntry");
        lwp('/r/Adaptor/HRMCommonI/handleEntry', { body: data }).then(res => {
            let responseText = "";
            try {
                responseText = JSON.parse(res.responseText);
            } catch (error) {
                responseText = res.responseText
            }
            if (res.statusCode === 200 && responseText) {
                const aflowUrl = responseText;
                this.setState({
                    aflowUrl,
                })
            }
        }).catch(err => {
            console.log(err);
        });
    }
    componentDidMount() {
        this.needReload();
        this.getHandleEntry();
    }

    resetRight() {
        if (this.state.total === 0 && !this.state.isLoading) {
            setRight({ show: false });
        }
    }
	/**
	 * 获取列表
	 * 
	 * @param {page: 页码, pageSize: 默认条数}
	 * */
    getLists = (pageNum,showLoading) => {
        this.props.actions
            .getLists({
                page: pageNum,
                pageSize: PAGE_SIZE
            }, showLoading)
            .then(res => {
                const data = [...this.state.data, ...res.result.data];
                this.setState({
                    dataSource: this.state.dataSource.cloneWithRows(data),
                    hasMore: res.result.hasMore,
                    isLoading: false,
                    total: res.result.total,
                    data
                });
            }, () => {
                if (this.state.total === 0) {
                    setRight({});
                }
            });
    };

	/**
	 * 下拉加载更多
	 * 
	 * 该组件有坑～
	 * https://github.com/ant-design/ant-design-mobile/issues/520#issuecomment-263510596
	 * */
    onEndReached = () => {
        console.log("end reached!!")
        if (!this.state.hasMore) {
            return;
        }
        const nextPage = this.state.pageIndex + 1;
        if (this.state.prePage !== nextPage) {
            this.state.prePage = nextPage;
            this.setState(
                {
                    isLoading: true,
                    pageIndex: nextPage,
                    prePage: nextPage
                },
                () => {
                    this.getLists(nextPage);
                }
            );
        }
    };

	/**
	 * 顶部下拉刷新页面(use html body as a scroll container.)
	 * */
    onRefresh = () => {
        console.log("onRefresh"); // eslint-disable-line
        this.setState({ refreshing: true });
        this.prePage = 1;
        setTimeout(() => {
            this.setState(
                {
                    dataSource: this.state.dataSource.cloneWithRows([]),
                    refreshing: false,
                    isLoading: true,
                    pageIndex: 1,
                    hasMore: false,
                    data: []
                },
                () => {
                    this.getLists(1);
                }
            );
        }, 1000);
    };
	/**
	 * 关闭顶部tips
	 */
    @autobind
    closeTips() {
        this.setState({ showTip: false })
    }
    render() {
        //在页面刷新的时候重新检查是否要改变右上角的扫码入职按钮
        this.resetRight();
        const t = this;
        const row = (rowData, sectionID, rowID) => {
            return (
                <div className="list-wrap preJob-list EMPlist">
                    <List className="my-list">
                        <Item
                            extra={
                                <div className="common-extra-btn"
                                    onClick={e => {
                                        // 防止触发整个行的onClick
                                        // 为了更容易触发点击，事件放在外层
                                        t.setState({needLoad:true})
                                        e.stopPropagation();
                                        window._rlog(`_prejob_to_confirm`);
                                        openLink(`?userId=${rowData.userId}#confirm`);
                                    }}>
                                    <button>确认到岗</button>
                                </div>
                                // <div>
                                //   确认到岗
                                // </div>
                            }
                            thumb={
                                <DDAvatar
                                    name={rowData.realName}
                                    size=""
                                    avatar={
                                        rowData.avatar &&
                                        mid2Url(rowData.avatar, { imageSize: "thumb" })
                                    }
                                    className="growth-avatar-dd-avatar"
                                    font=""
                                />
                            }
                            multipleLine
                            onClick={() => {
                                window._rlog(`_prejob_to_preview`);
                                (openLink(`?userId=${rowData.userId}#preview`))
                            }
                            }
                        >
                            <h4 className="full-name">{rowData.realName}</h4>
                            <Brief>
                                {
                                    <p className="last-date">
                                        {
                                            rowData.confrimJoinTime ?
                                                rowData.confrimJoinTime :
                                                "未设置"
                                        }
                                    </p>
                                }
                                {
                                    <p className="list-from">
                                        {getFromMessage(rowData.opUserName, rowData.opSourceType)}
                                    </p>
                                }
                                {
                                    rowData.submitRegistration
                                        ? <p className="list-status">已提交入职登记表</p>
                                        : <p className="list-status no-submit">未提交入职登记表</p>
                                }
                            </Brief>
                        </Item>
                    </List>
                </div>
            )}

        return (
            <div id="prejob-list">
                {this.state.total !== 0 &&
                    <div>
                        <ListView
                            ref={el => (this.lv = el)}
                            renderHeader={() => this.renderListHeader()}
                            dataSource={this.state.dataSource}
                            renderRow={row}
                            pageSize={10}
                            style={{
                                height: this.state.height
                            }}
                            scrollEventThrottle={200}
                            onEndReached={this.onEndReached}
                            onEndReachedThreshold={10}
                        />
                    </div>
                }

                {this.state.total === 0 && !this.state.isLoading &&<div>
                    
                    <div className="preJob no-data">
                        <img
                            src="https://gw.alicdn.com/tfs/TB1CfRsmgMPMeJjy1XdXXasrXXa-174-204.png"
                            alt=""
                        />
                        <p className="no-data-big-text">提前收集入职信息做好入职准备</p>
                        <p className="no-data-small-text">当前暂无待入职员工</p>
                    </div>
                    {this.renderListHeader()}
                    </div>
                }
            </div>
        );
    }

    renderListHeader() {
        const t = this;
        return <div>
            <div className="prejob-banner">
                <div
                    className="prejob-banner-col"
                    onClick={() => {
                        const color = {
                            dd_nav_bgcolor: "FF4BA2FA"
                        }
                        const url = replaceSearch(color);
                        openLink(url + "#/qrCode");
                    }}>
                    <img
                        src="https://gw.alicdn.com/tfs/TB1MkaEaiqAXuNjy1XdXXaYcVXa-104-104.png"
                        className="prejob-banner-col-image" />
                    <div className="prejob-banner-col-text">扫码入职</div>
                </div>
                <div
                    className="prejob-banner-col"
                    onClick={() => {
                        t.setState({aflowLoad:true})
                        openLink(this.state.aflowUrl || '')}
                        }>
                    <img
                        src="https://gw.alicdn.com/tfs/TB14QeEaiqAXuNjy1XdXXaYcVXa-104-104.png"
                        className="prejob-banner-col-image" />
                    <div className="prejob-banner-col-text">审批入职</div></div>
                <div
                    className="prejob-banner-col"
                    onClick={() => openLink('https://tms.dingtalk.com/markets/dingtalk/shoudongtianjia-shouji?wh_ttid=phone')}>
                    <img
                        src="https://gw.alicdn.com/tfs/TB1bkmEaiqAXuNjy1XdXXaYcVXa-104-104.png"
                        className="prejob-banner-col-image" />
                    <div className="prejob-banner-col-text">手动添加</div></div>
            </div>
            <div className="phone-border-fix"></div>
            {
                this.state.total !== 0 ? <div>
                    <WhiteSpace size="lg"></WhiteSpace>
                    <TitleBage title={`待入职员工 ${this.state.total}`}></TitleBage>
                </div> : ""
            }
            {
                this.state.showTip &&
                <div className="preJob-tip">
                    <span>
                        <img src="https://img.alicdn.com/tfs/TB158V_rgMPMeJjy1XcXXXpppXa-84-84.png" alt="" />
                        确认入职后，员工会加入到钉钉通讯录。
								</span>
                    <Icon type="cross" onClick={this.closeTips} />
                </div>
            }
        </div>
    }
}